using B.S.XZYData.Api.Read.Application.Command.Permission;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Permission
{
    public class GetAllPermissionHandler : IRequestHandler<GetAllPermissionCommand, ApiResult<List<PermissionModel>>>
    {
        private readonly IBaseRepository<PermissionModel> _permissionRepo;
        public GetAllPermissionHandler(IBaseRepository<PermissionModel> permissionRepo)
        {
            _permissionRepo = permissionRepo;
        }
        public async Task<ApiResult<List<PermissionModel>>> Handle(GetAllPermissionCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<List<PermissionModel>>();
            try
            {
                var list = _permissionRepo.GetAll().Where(x => !x.IsDeleted).ToList();
                
                // 构建权限映射表用于获取父级权限名称
                var permissionMap = list.ToDictionary(x => x.Id, x => x.PermissionName);
                
                // 设置父级权限名称
                foreach (var item in list)
                {
                    if (item.ParentId > 0 && permissionMap.ContainsKey(item.ParentId))
                    {
                        item.ParentName = permissionMap[item.ParentId];
                    }
                    else
                    {
                        item.ParentName = string.Empty;
                    }
                }
                
                res.Data = list;
                res.Msg = "查询所有权限成功!";
                res.Code = ApiEnum.Success;
            }
            catch (Exception ex)
            {
                res.Data = null;
                res.Msg = "查询所有权限异常：" + ex.Message;
                res.Code = ApiEnum.Error;
            }
            return await Task.FromResult(res);
        }
    }
} 